package com.example.config;

import com.example.repository.HibernateStudentRepository;
import com.example.repository.impl.HibernateStudentRepositoryImpl;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class SessionFactoryConfig {

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("org.h2.Driver");
        driverManagerDataSource.setUrl("jdbc:h2:mem:test;MODE=MYSQL;DB_CLOSE_DELAY=-1");
        driverManagerDataSource.setUsername("sa");
        driverManagerDataSource.setPassword("");
        return driverManagerDataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource){
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(dataSource);
        localSessionFactoryBean.setPackagesToScan("com.example.entity");
        localSessionFactoryBean.setHibernateProperties(hibernateProperties());
        return localSessionFactoryBean;
    }

    private Properties hibernateProperties(){
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        //Drop and re-create the database schema on startup
        // 注意，key必须使用"hibernate.hbm2ddl.auto"而不是"hbm2ddl.auto"
        // 因为，经测试，key设置为"hbm2ddl.auto"的时候，配置不生效，无法自动创建数据库表
        // 把"hibernate."前缀加上之后就没有这个问题
        // 但是使用hibernate.cfg.xml来配置的话，使用hbm2ddl.auto是没有问题的
        props.setProperty("hibernate.hbm2ddl.auto", "create");
        return props;
    }

}
